package com.samshow.dao;


import com.samshow.entity.UserEntity;
import com.samshow.vo.Privilege;
import com.samshow.vo.ResourcePrivilege;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2016/11/3.
 */
public class MyJdbcQuery {

    public MyJdbcQuery(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private JdbcTemplate jdbcTemplate;



    public List<Privilege> getUserPrivilege(int userId) {
        String sql = "SELECT privilege FROM user_privilege up, privilege_ p WHERE up.privilege_id= p.id AND up.user_id = ?";
        List<String> strings = jdbcTemplate.queryForList(sql, String.class, userId);
        List<Privilege> privileges = new ArrayList<Privilege>(strings.size());
        privileges.addAll(strings.stream().map(Privilege::valueOf).collect(Collectors.toList()));
        return privileges;
    }

    public UserEntity getUser4Auth(String userName) {
        UserEntity user = jdbcTemplate.queryForObject(
                "select * from user_ where username = ?", new BeanPropertyRowMapper<UserEntity>(UserEntity.class), userName);
        return user;
    }


    public List<ResourcePrivilege> gePrivilegResource(){
        String sql = "SELECT resource,privilege  FROM resource_ r,privilege_ p,privilege_resource pr WHERE r.id = pr.resource_id AND p.id = pr.privilege_id";
        List<ResourcePrivilege> resourceList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<ResourcePrivilege>(ResourcePrivilege.class));
        return resourceList;
    }


}
